<template>
  <div>
    <el-form ref="form" :inline="true" label-width="100px" class="mt-20 searchbar-box clearfix">
      <el-button class="mr-10" @click="goPage('add')" type="primary" icon="el-icon-plus" v-if="menuPermission.includes('create')">添加企业</el-button>
      <template v-if="menuPermission.includes('search')">
        <el-form-item label="企业名称">
          <el-input v-model="searchParams.name" placeholder=" 输入企业名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="searchParams.principal" placeholder=" 输入负责人名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="区县">
          <el-cascader v-model="searchParams.areaArr" :options="addressOptions" placeholder="请选择" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchParams.enterpriseType" placeholder="请选择" clearable>
            <el-option v-for="(propValue,propKey) in enterpriseTypeMap" :key="propKey" :label="propValue" :value="propKey"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="interSearch">查询结果</el-button>
        </el-form-item>
      </template>
      <el-form-item class="fr" v-if="menuPermission.includes('import')">
        <el-popover
          placement="top-start"
          width="300"
          trigger="hover">
          <a class="c-blue mr-20" :href="fileLink1">养殖企业模板下载</a>
          <a class="c-blue" :href="fileLink2">非养殖企业模板下载</a>
          <a class="c-blue mr-20" slot="reference">模板下载</a>
        </el-popover>
        <el-popover
          placement="top-start"
          width="300"
          trigger="hover">
          <a class="c-blue mr-20" @click="handelImport(1)">养殖企业数据导入</a>
          <a class="c-blue" @click="handelImport(0)">非养殖企业数据导入</a>
          <el-button slot="reference" type="primary">导入数据</el-button>
        </el-popover>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" :empty-text="emptyText" v-loading="isLoading" element-loading-text="加载中..." stripe="stripe">
      <template v-for="(item, index) of tableColu">
        <el-table-column :key="index + item.prop" :label="item.title" align="center" :show-overflow-tooltip="true" :min-width="item.minWidth" :width="item.width"
          :render-header="renderheader">
          <template slot-scope="scope">
            <span v-if="item.prop === 'addressAll'">
              {{scope.row['areaName'].replace('/','').replace('/','')}} {{scope.row['address']}}
            </span>
            <span v-else-if="item.prop === 'enterpriseType'">
              {{enterpriseTypeMap[scope.row[item.prop]]}}
            </span>
            <span v-else-if="item.prop === 'isAuthField'">
              {{scope.row[item.prop] === 1? '是' : scope.row[item.prop] === 0? '否' : ''}}
            </span>
            <span v-else-if="item.prop === 'isDataField'">
              {{scope.row[item.prop] === 1? '是' : scope.row[item.prop] === 0? '否' : ''}}
            </span>
            <div v-else-if="item.prop==='operation'">
              <el-tooltip class="item" content="查看" placement="top-start">
                <svg-icon @click="goPage('view', scope.row)" class="can-click" icon-class="view" />
              </el-tooltip>
              <el-tooltip class="item" content="编辑" placement="top-start" v-if="menuPermission.includes('update')">
                <svg-icon @click="goPage('edit', scope.row)" class="can-click" icon-class="note" />
              </el-tooltip>
              <!--<el-tooltip class="item" content="绑定" placement="top-start" v-if="menuPermission.includes('bind')">-->
                <!--<svg-icon @click="handelBind(scope.row)" class="can-click" icon-class="binding" />-->
              <!--</el-tooltip>-->
              <el-tooltip class="item" content="删除" placement="top-start" v-if="menuPermission.includes('delete')">
                <svg-icon @click="handelDelete(scope.row)" class="can-click" icon-class="delete" />
              </el-tooltip>
            </div>
            <span v-else>{{scope.row[item.prop]}}</span>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination class="mt-30" :current-page="searchParams.currentPage" :page-size="searchParams.pageSize" :total="total" layout="sizes, total, prev, pager, next, jumper"
      @current-change="handleCurrentChange" @size-change="handleSizeChange"></el-pagination>
    <el-dialog :visible.sync="dialogVisibleExcel" width="500px" center>
      <el-upload ref="upload" drag action="#" accept=".xlsx" :limit="1" :http-request="fileChange" :on-remove="handleFileRemove" :on-exceed="handleExceed" style="width: 360px;">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </el-upload>
      <div class="text-center">
        <el-button @click="dialogVisibleExcel=false">取 消</el-button>
        <el-button type="primary" @click="onSubmitUpload">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog width="500px" title="绑定设备中台企业" :visible.sync="dialogVisibleBind" :close-on-click-modal="false" @close="closeDialog('formData')">
      <el-form ref="formData" :model="formData">
        <el-form-item label="企业">
          <el-select v-model="formData.iotEnterpriseId" filterable placeholder="请选择企业" :disabled="bindStatus !='BIND'">
            <el-option v-for="item in bindIotEnterpriseList" :key="item.compId" :label="item.compFullName" :value="item.compId" />
          </el-select>
          <p :class="statusColor">{{bindEnterpriseName}}</p>
        </el-form-item>
      </el-form>
      <div class="text-center">
        <el-button @click="dialogVisibleBind=false">取 消</el-button>
        <el-button type="primary" @click="onSubmitBind">{{bindBtn}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'dataManage',
  data () {
    return {
      isLoading: false,
      emptyText: '加载中...',
      tableColu: [
        { title: '企业名称', prop: 'name', minWidth: '100', width: null },
        { title: '企业类型', prop: 'enterpriseType', minWidth: '100', width: null },
        { title: '负责人', prop: 'principal', minWidth: '', width: null },
        { title: '联系电话', prop: 'mobile', minWidth: '100', width: null },
        { title: '所属地区', prop: 'areaName', minWidth: '100', width: null },
        { title: '详细地址', prop: 'address', minWidth: '100', width: null },
        { title: '是否数字禽场', prop: 'isDataField', minWidth: '100', width: null },
        { title: '是否认证禽场', prop: 'isAuthField', minWidth: '100', width: null },
        // { title: '是否启用', prop: 'address', minWidth: '100', width: null },

        { title: '操作', prop: 'operation', minWidth: '100', width: '' }
      ],
      tableData: [],
      total: 0,
      searchParams: {
        keyword: '',
        currentPage: 1,
        pageSize: 20
      },
      dialogVisibleExcel: false,
      file: null,
      fileLink1: process.env.VUE_APP_COMPANY_FILE_EDOWNLOAD_API + '养殖企业数据导入模板最新.xlsx',
      fileLink2: process.env.VUE_APP_COMPANY_FILE_EDOWNLOAD_API + '非养殖企业数据导入模板最新 .xlsx',
      dialogVisibleBind: false,
      isBind: true,
      bindIotEnterpriseList: [],
      formData: {
        iotEnterpriseId: ''
      },
      bindBtn: '绑定设备中台',
      bindStatus: 'BIND',
      bindEnterpriseName: '',
      statusColor: '',
      menuPermission: [],
      addressOptions: [{ value: '肇庆市', label: '肇庆市', children: [{ value: '端州区', label: '端州区', children: [{ value: '城东', label: '城东' }, { value: '城西', label: '城西' }, { value: '城南', label: '城南' }, { value: '城北', label: '城北' }, { value: '康乐', label: '康乐' }, { value: '古塔', label: '古塔' }] }, { value: '鼎湖区', label: '鼎湖区', children: [{ value: '坑口街道', label: '坑口街道' }, { value: '桂城街道', label: '桂城街道' }, { value: '广利街道', label: '广利街道' }, { value: '永安镇', label: '永安镇' }, { value: '沙浦镇', label: '沙浦镇' }, { value: '凤凰镇', label: '凤凰镇' }, { value: '莲花镇', label: '莲花镇' }] }, { value: '广宁县', label: '广宁县', children: [{ value: '南街镇', label: '南街镇' }, { value: '赤坑镇', label: '赤坑镇' }, { value: '北市镇', label: '北市镇' }, { value: '江屯镇', label: '江屯镇' }, { value: '联和镇', label: '联和镇' }, { value: '潭布镇', label: '潭布镇' }, { value: '排沙镇', label: '排沙镇' }, { value: '石涧镇', label: '石涧镇' }, { value: '宾亨镇', label: '宾亨镇' }, { value: '横山镇', label: '横山镇' }, { value: '五和镇', label: '五和镇' }, { value: '木格镇', label: '木格镇' }, { value: '洲仔镇', label: '洲仔镇' }, { value: '古水镇', label: '古水镇' }, { value: '坑口镇', label: '坑口镇' }, { value: '葵洞镇', label: '葵洞镇' }, { value: '螺岗镇', label: '螺岗镇' }, { value: '清桂镇', label: '清桂镇' }, { value: '石咀镇', label: '石咀镇' }, { value: '深坑乡', label: '深坑乡' }] }, { value: '怀集县', label: '怀集县', children: [{ value: '梁村镇', label: '梁村镇' }, { value: '大岗镇', label: '大岗镇' }, { value: '岗坪镇', label: '岗坪镇' }, { value: '冷坑镇', label: '冷坑镇' }, { value: '马宁镇', label: '马宁镇' }, { value: '蓝钟镇', label: '蓝钟镇' }, { value: '怀城镇', label: '怀城镇' }, { value: '闸岗镇', label: '闸岗镇' }, { value: '坳仔镇', label: '坳仔镇' }, { value: '汶朗镇', label: '汶朗镇' }, { value: '甘洒镇', label: '甘洒镇' }, { value: '凤岗镇', label: '凤岗镇' }, { value: '洽水镇', label: '洽水镇' }, { value: '中洲镇', label: '中洲镇' }, { value: '连麦镇', label: '连麦镇' }, { value: '永固镇', label: '永固镇' }, { value: '诗洞镇', label: '诗洞镇' }, { value: '桥头镇', label: '桥头镇' }, { value: '下帅乡', label: '下帅乡' }] }, { value: '封开县', label: '封开县', children: [{ value: '长岗镇', label: '长岗镇' }, { value: '江口镇', label: '江口镇' }, { value: '南丰镇', label: '南丰镇' }, { value: '平凤镇', label: '平凤镇' }, { value: '大洲镇', label: '大洲镇' }, { value: '都平镇', label: '都平镇' }, { value: '江川镇', label: '江川镇' }, { value: '大玉口镇', label: '大玉口镇' }, { value: '河儿口镇', label: '河儿口镇' }, { value: '长安镇', label: '长安镇' }, { value: '金装镇', label: '金装镇' }, { value: '白垢镇', label: '白垢镇' }, { value: '莲都镇', label: '莲都镇' }, { value: '渔涝镇', label: '渔涝镇' }, { value: '杏花镇', label: '杏花镇' }, { value: '罗董镇', label: '罗董镇' }] }, { value: '德庆县', label: '德庆县', children: [{ value: '新圩镇', label: '新圩镇' }, { value: '官圩镇', label: '官圩镇' }, { value: '马圩镇', label: '马圩镇' }, { value: '高良镇', label: '高良镇' }, { value: '莫村镇', label: '莫村镇' }, { value: '永丰镇', label: '永丰镇' }, { value: '武垄镇', label: '武垄镇' }, { value: '播植镇', label: '播植镇' }, { value: '凤村镇', label: '凤村镇' }, { value: '九市镇', label: '九市镇' }, { value: '悦城镇', label: '悦城镇' }] }, { value: '高要市', label: '高要市', children: [{ value: '南岸街道', label: '南岸街道' }, { value: '河台镇', label: '河台镇' }, { value: '乐城镇', label: '乐城镇' }, { value: '水南镇', label: '水南镇' }, { value: '禄步镇', label: '禄步镇' }, { value: '小湘镇', label: '小湘镇' }, { value: '大湾镇', label: '大湾镇' }, { value: '新桥镇', label: '新桥镇' }, { value: '白诸镇', label: '白诸镇' }, { value: '长安镇', label: '长安镇' }, { value: '莲塘镇', label: '莲塘镇' }, { value: '活道镇', label: '活道镇' }, { value: '蛟塘镇', label: '蛟塘镇' }, { value: '回龙镇', label: '回龙镇' }, { value: '白土镇', label: '白土镇' }, { value: '金渡镇', label: '金渡镇' }, { value: '金利镇', label: '金利镇' }, { value: '蚬岗镇', label: '蚬岗镇' }] }, { value: '四会市', label: '四会市', children: [{ value: '东城街道', label: '东城街道' }, { value: '城中街道', label: '城中街道' }, { value: '贞山街道', label: '贞山街道' }, { value: '龙甫镇', label: '龙甫镇' }, { value: '地豆镇', label: '地豆镇' }, { value: '威整镇', label: '威整镇' }, { value: '罗源镇', label: '罗源镇' }, { value: '迳口镇', label: '迳口镇' }, { value: '大沙镇', label: '大沙镇' }, { value: '石狗镇', label: '石狗镇' }, { value: '下茆镇', label: '下茆镇' }, { value: '江谷镇', label: '江谷镇' }, { value: '黄田镇', label: '黄田镇' }] }] }],
      regionSearch: [
        { value: '0', label: '牡丹区' },
        { value: '5', label: '其他区县' },
      ],
      enterpriseTypeMap: { //企业类型
        0: '孵化场',
        1: '养殖场',
        2: '饲料厂',
        3: '屠宰场',
        4: '食品加工厂',
        5: '育种场',
        6: '销售网点',
        7: '其他企业',
      },
      uploadEnterpriseType: '',
    };
  },
  mounted () {
    this.getDataList();
    this.menuPermission = this.$route.meta.rights || this.$route.matched[1].meta.rights
    this.menuPermission = this.menuPermission ? this.menuPermission.split(',') : []
    console.log('this.menuPermission', this.menuPermission)
    // let vm = this
    // this.$bus.$on('refreshDataList', () => {
    //   vm.getDataList()
    // })
    this.getIotEnterpriseList()
  },
  methods: {
    renderheader (h, { column }) {
      return h('span', {}, [
        h('span', {}, column.label.split('/')[0]),
        h('br'),
        h('span', {}, column.label.split('/')[1])
      ])
    },
    /* 获取列表数据 */
    getDataList (currentPage) {
      // console.log(this.$store.state.user)
      this.isLoading = true;
      this.searchParams.currentPage = currentPage || 1;
      var param = {
        projectId: this.$store.state.user.projectId,
        currentPage: this.searchParams.currentPage,
        pageSize: this.searchParams.pageSize,
        name: this.searchParams.name,
        principal: this.searchParams.principal,
        enterpriseType: this.searchParams.enterpriseType && parseInt(this.searchParams.enterpriseType),
        areaName: this.searchParams.areaArr && this.searchParams.areaArr.join('/'),
        source: 0
      }
      this.$api.data.getListEnterpriseInfo(param).then(res => {
        this.isLoading = false;
        this.total = res.total;
        this.tableData = res.data || [];
        this.emptyText = !this.tableData.length ? '暂无数据' : this.emptyText;
      });
    },
    /* 点击搜索按钮进行搜索 */
    interSearch () {
      this.getDataList();
    },
    /* 清空筛选条件 */
    clearSearchParam () {
      this.searchParams.keyword = '';
      this.getDataList();
    },
    /* 导入 */
    handelImport (uploadEnterpriseType) {
      this.uploadEnterpriseType = uploadEnterpriseType
      this.dialogVisibleExcel = true;
    },
    /* 查看&新增&编辑 */
    goPage (url, obj) {
      console.log(url, obj)
      let query = {
        type: url
      }
      if (url !== 'add') {
        query.id = obj.enterpriseId
      }
      this.$router.push({
        path: `/dataManage/${url}`,
        query: query
      })
    },
    /* 绑定 */
    handelBind (item) {
      let val = JSON.parse(JSON.stringify(item));
      this.formData.itemEnterpriseId = val.enterpriseId;
      if (val.iotEnterpriseId) {
        let bindIotEnterprise = this.bindIotEnterpriseList.find(item => item.compId === val.iotEnterpriseId) || {};
        let bindIotEnterpriseName = bindIotEnterprise.compFullName || '';
        this.formData.iotEnterpriseId = val.iotEnterpriseId;
        this.bindEnterpriseName = '已绑设备中台：' + bindIotEnterpriseName
        this.bindBtn = '取消绑定';
        this.bindStatus = 'UNBIND';
      } else {
        let bindIotEnterprise = this.bindIotEnterpriseList[0] || {};
        this.formData.iotEnterpriseId = bindIotEnterprise.compId;
        this.bindEnterpriseName = '';
        this.bindBtn = '绑定设备中台';
        this.bindStatus = 'BIND';
      }

      this.dialogVisibleBind = true;
    },
    closeDialog (formName) {
      this.dialogVisibleBind = false;
      this.$refs[formName].resetFields();
    },
    onSubmitBind () {
      let msg = this.bindStatus === 'BIND' ? '绑定' : '解绑';
      let bindIotEnterprise = this.bindIotEnterpriseList.find(item => item.compId === this.formData.iotEnterpriseId);
      if (!bindIotEnterprise) {
        this.$message.error(`请选择要${msg}的企业`);
        return;
      }
      let bindIotEnterpriseName = bindIotEnterprise.compFullName || '';
      this.$confirm(`确定要${msg}${bindIotEnterpriseName}这个企业吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.data.operateEnterpriseInfo({
          enterpriseId: this.formData.itemEnterpriseId,
          iotEnterpriseId:this.formData.iotEnterpriseId,
          operateType: this.bindStatus,
          name: bindIotEnterpriseName
        }).then(res => {
          let exist = res.data || ''
          if (exist === 1) {
            if (this.bindStatus === 'BIND') {
              this.bindEnterpriseName = '已绑设备中台：' + bindIotEnterpriseName;
              this.bindBtn = '取消绑定';
              this.bindStatus = 'UNBIND';
              this.statusColor = 'successColor';
            } else {
              this.bindEnterpriseName = '已取消绑设备中台：' + bindIotEnterpriseName;
              this.bindBtn = '绑定设备中台';
              this.bindStatus = 'BIND';
              this.statusColor = 'failColor';
            }
          } else {
            this.bindEnterpriseName = '设备中台找不到该企业';
            this.bindBtn = '绑定设备中台';
            this.bindStatus = 'BIND';
            this.statusColor = 'failColor';
          }
          this.getDataList(this.searchParams.currentPage);
        })
      }).catch(() => {
      });
    },
    /* 删除 */
    handelDelete (obj) {
      this.$confirm(`确定要删除${obj.name}这个企业吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.data.operateEnterpriseInfo({
          enterpriseId: obj.enterpriseId,
          operateType: 'DELETE'
        }).then(() => {
          this.$message({
            type: 'success',
            message: `删除成功!`
          });
          this.getDataList()
        })
      }).catch(() => {
      });
    },
    handleCurrentChange (val) {
      this.searchParams.currentPage = val
      this.getDataList(val)
    },
    handleSizeChange (val) {
      this.searchParams.pageSize = val
      this.searchParams.currentPage = 1
      this.getDataList()
    },
    /* 导入 */
    fileChange (param) {
      this.file = param.file
    },
    handleFileRemove () {
      this.file = null
    },
    handleExceed () {
      this.$alert('当前限制选择 1 个文件，请先移除！', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false
      });
    },
    onSubmitUpload () {
      var formData = new FormData();
      formData.append('file', this.file)
      formData.append('enterpriseType', this.uploadEnterpriseType)
      formData.append('projectId', this.$store.state.user.projectId)
      if (this.file) {
        this.$api.data.importEnterpriseInfo(formData).then(() => {
          this.dialogVisibleExcel = false;
          this.$message.success('导入成功！')
          this.getDataList();
        }).catch(() => {
          this.$message.warning('导入失败！')
        })
      } else {
        this.$message.warning('请上传Excel文件！')
      }
    },
    getIotEnterpriseList () {
      let params = {
        currentPage: 1,
        pageSize: 100000
      };
      this.$api.data.getIotEnterpriseList(params).then(res => {
        this.bindIotEnterpriseList = res.data || [];
      });
    }
  }
}
</script>
